import { _decorator, Component, Node, Prefab, instantiate, director, Label } from 'cc'
import { ApiMsgEnum, IMsgGameStart, IMsgRoom } from '../Common'
import { SceneEnum } from '../Enum'
import DataManager from '../Global/DataManager'
import { NetworkManager } from '../Global/NetworkManager'
import { PlayerManager } from '../UI/PlayerManager'
import { deepClone } from '../Utils'

const { ccclass, property } = _decorator

// 房间场景
@ccclass('RoomManager')
export class RoomManager extends Component {
  @property(Node)
  playerContainer: Node

  @property(Prefab)
  playerPrefab: Prefab

  private roomName: Label

  onLoad() {
    // 同步房间内的玩家信息
    NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers, this)
    // 游戏开始 同步玩家信息
    NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this)

    this.roomName = this.node.getComponentInChildren(Label)
    this.roomName.string = DataManager.Instance.roomInfo.id + '号房间'
  }

  start() {
    this.renderPlayers({
      room: DataManager.Instance.roomInfo,
    })
  }

  onDestroy() {
    NetworkManager.Instance.unListenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers, this)
    NetworkManager.Instance.unListenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this)
  }

  // 渲染玩家列表
  renderPlayers({ room: { players: list } }: IMsgRoom) {
    // 隐藏所有节点
    for (const child of this.playerContainer.children) {
      child.active = false
    }
    // 生成等长节点
    while (this.playerContainer.children.length < list.length) {
      const node = instantiate(this.playerPrefab)
      node.active = false
      node.setParent(this.playerContainer)
    }
    // 节点显示和赋值
    for (let i = 0; i < list.length; i++) {
      const data = list[i]
      const node = this.playerContainer.children[i]
      node.getComponent(PlayerManager).init(data)
    }
  }

  // 玩家离开房间
  async handleLeaveRoom() {
    const { success, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiRoomLeave, {})
    if (!success) return console.log('api错误：', error)
    DataManager.Instance.roomInfo = null
    director.loadScene(SceneEnum.Hall)
  }

  // 客户点击-->开始游戏
  async handleStartGame() {
    const { success, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiGameStart, {})
    if (!success) return console.log('api错误：', error)
  }

  // 服务返回-->游戏开始
  async handleGameStart({ state }: IMsgGameStart) {
    DataManager.Instance.state = state
    DataManager.Instance.lastState = deepClone(state)
    director.loadScene(SceneEnum.Battle)
  }
}
